# 存储需求单
import sys
sys.path.append("..")
import json
from flask import request
from create_id import get_id
from db_client import *

def store_demand():
    # 存储需求单
    token = request.headers.get('token')
    flag, right = token_client.check_token(token)
    if not flag:
        t = {
            'state': 'false',
            'msg': '存储需求单失败, 登陆已过期，请重新登陆'
        }
        return json.dumps(t, ensure_ascii=False)
    else:
        data = json.loads(request.get_data().decode('utf-8'))
        department = data['demand_department']
        item_id = data['demand_item_id']
        item_name = data['demand_item_name']
        item_count = data['demand_item_count']
        date = data['demand_date']
        input_person = data['demand_input_person']
        demand_file_id = data['demand_file_id']

        sid = get_id('XQ')

        #检测需求文件编号
        if demand_file_id:
            result = mysql_client.check_demand_file(demand_file_id)
            if not result:
                t = {
                'state': 'false',
                'msg': '需求文件编号错误。'
                }
                return json.dumps(t, ensure_ascii=False)

        #检测物品编号        
        check_item = mysql_client.check_item_num(item_id)
        if not check_item:
            t = {
            'state': 'false',
            'msg': '物品编号错误，或物品不存在。'
            }
            return json.dumps(t, ensure_ascii=False)

        #检测物品编号与名称是否对应
        check_item_name = mysql_client.search_item_name(item_id)
        #print(check_item_name, item_name)
        if check_item_name != item_name:
            t = {
            'state': 'false',
            'msg': '物品名称与编号不对应，请检查。'
            }
            return json.dumps(t, ensure_ascii=False)


        flag2 = mysql_client.store_demand(sid, department, item_id, item_name, item_count, date, input_person, demand_file_id)
        if flag2:
            t = {
                'state': 'true',
                'msg': 'success'
            }
            return json.dumps(t, ensure_ascii=False)
        else:
            t = {
                'state': 'false',
                'msg': '提交需求单失败，稍后再试。'
            }
            return json.dumps(t, ensure_ascii=False)

